package List

//线性表
type ElemType struct {
	Data   []interface{}
	length int
	cap    int
}

func NewElem(len int) ElemType {
	return ElemType{
		Data:   make([]interface{}, len, len),
		length: 0,
		cap:    len,
	}

}

//获取一个元素, 支持负数索引
func (e *ElemType) GetElem(i int) (interface{}, error) {
	if e.length == 0 || i >= e.length || i < e.length*(-1) {
		return nil, IndexErr
	}

	if i < 0 { //转换
		i = e.length + i
	}

	return e.Data[i], nil

}

//插入数据
func (e *ElemType) Insert(item interface{}, i int) error {
	if e.length == e.cap {
		return CapMaxErr
	}

	if i < 0 { //转换
		i = e.length + i
	}

	if i < 0 || i >= e.cap {
		return IndexErr
	}

	//再表尾
	if i == e.length {
		e.Data[i] = item
	} else {
		for j := e.length - 1; j >= i; j-- {
			e.Data[j+1] = e.Data[j] //后移
		}
		e.Data[i] = item
	}

	e.length += 1

	return nil

}

func (e *ElemType) Pop(i int) (interface{}, error) {
	if i < 0 {
		i = i + e.length
	}

	if i < 0 || i >= e.length || e.length == 0 {
		return nil, IndexErr
	}

	k := e.Data[i]
	if i == e.length-1 { //最后一位

		e.Data[i] = nil
		return k, nil
	} else { //中间
		for j := i + 1; j < e.length; j++ {
			e.Data[j-1] = e.Data[j]
		}
	}
	e.length -= 1
	return k, nil

}

func (e *ElemType) Length() int {
	return e.length
}
